<template>
  <div class="content flex">
    <StudentMenu />
    <main class="ml-64 flex-1 p-6 bg-gray-50 min-h-screen">
      <header class="flex justify-between items-center mb-4">
        <h1 class="text-2xl font-bold">视频瀑布流</h1>
      </header>

      <div class="flex justify-between items-center mb-4">
        <el-input v-model="searchText" placeholder="搜索"></el-input>
        <el-button type="primary" @click="askForVideo">请求视频</el-button>
      </div>

      <!-- 分列瀑布流 -->
      <div class="masonry">
        <div
            v-for="(column, colIndex) in columns"
            :key="colIndex"
            class="column"
        >
          <div
              v-for="(video, idx) in column"
              :key="colIndex + '-' + idx"
              class="masonry-item bg-white rounded-lg p-2 mb-4"
          >
            <video
                :ref="el => setVideoRef(el, video.globalIndex)"
                :poster="video.CoverUrl"
                :src="video.url"
                class="w-full rounded"
                controls
                preload="metadata"
                @play="onPlay(video.globalIndex)"
            ></video>
            <p class="mt-2 text-sm text-gray-700">{{ video.caption}}</p>
            <div class="mt-2 flex justify-end space-x-2">
              <el-button size="mini" @click="playFullscreen(video.globalIndex)">全屏播放</el-button>
              <el-button size="mini" @click="playNext(video.globalIndex)">下一个</el-button>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script>
import StudentMenu from "@/components/student/Student_menu.vue";
import axios from 'axios';
import SockJS from "sockjs-client";
import { NOWIP } from "@/NOWIP";
import Stomp from "webstomp-client";

export default {
  name: "VideoMasonry",
  components: { StudentMenu },
  data() {
    return {
      searchText: '就业',
      UserInfo: {id: '', name: '', role: '', username: ''},
      videos: [],           // 全局列表，用于索引控制播放
      bufferedVideos: [],
      updateTimer: null,
      stompClient: null,
      currentIdx: null,
      videoRefs: {}         // 存储视频元素引用
    };
  },
  computed: {
    // 将全局 videos 按列分配，round-robin
    columns() {
      const cols = Array.from({length: 6}, () => []);
      this.videos.forEach((video, idx) => {
        const col = idx % 6;
        cols[col].push({...video, globalIndex: idx});
      });
      return cols;
    }
  },
  methods: {
    setVideoRef(el, idx) {
      if (el) this.$set(this.videoRefs, idx, el);
    },
    async getLoginUserInfo() {
      try {
        const response = await axios.get(`/api/user/info`);
        this.UserInfo = response.data;
      } catch (error) {
        console.error('获取用户信息失败', error);
      }
    },
    onPlay(idx) {
      this.currentIdx = idx;
      Object.entries(this.videoRefs).forEach(([key, vid]) => {
        if (Number(key) !== idx && !vid.paused) {
          vid.pause();
        }
      });
    },
    playFullscreen(idx) {
      const vid = this.videoRefs[idx];
      if (!vid) return;
      this.onPlay(idx);
      vid.requestFullscreen?.() || vid.webkitRequestFullScreen?.();
      vid.play();
    },
    playNext(idx) {
      const next = (idx + 1) % this.videos.length;
      if (this.currentIdx != null) {
        const currentVid = this.videoRefs[this.currentIdx];
        if (currentVid && !currentVid.paused) currentVid.pause();
      }
      this.currentIdx = next;
      const vidNext = this.videoRefs[next];
      if (vidNext) {
        vidNext.play();
        document.fullscreenElement && vidNext.requestFullscreen?.();
      }
    },
    connectWebSocket() {
      const socket = new SockJS(`http://${NOWIP}:83/chat`);
      this.stompClient = Stomp.over(socket);
      this.stompClient.connect({}, () => {
        this.stompClient.subscribe('/topic/videos', msg => {
          const video = JSON.parse(msg.body);
          this.bufferedVideos.push({url: video.splj, CoverUrl: video.CoverUrl, caption: video.spbt});
        });
      });
    },
    askForVideo() {
      const payload = {
        gjc: this.searchText,
        hqsj: Date.now(),
        yhm: this.UserInfo.username,
        yhsfdm: 4
      };
      try {
        this.stompClient.send("/app/broadcast", JSON.stringify(payload));
      } catch (error) {
        console.error('消息发送失败', error);
      }
    }
  },
  mounted() {
    this.getLoginUserInfo();
    this.connectWebSocket();
    this.updateTimer = setInterval(() => {
      if (this.bufferedVideos.length) {
        this.videos.push(...this.bufferedVideos.splice(0));
      }
    }, 1000);
  },
  beforeUnmount() {
    this.stompClient?.disconnect();
    clearInterval(this.updateTimer);
  }
};
</script>

<style scoped>
.masonry {
  display: flex;
  gap: 16px;
}

.column {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.masonry-item {
  display: flex;
  flex-direction: column;
}

@media (max-width: 1200px) {
  .masonry {
    gap: 8px;
  }
}

@media (max-width: 768px) {
  .masonry {
    flex-direction: column;
  }
}
</style>
